<template>
  <div class="system-dict">
    <div class="section-container">
      <div class="section-title">
        字典管理
      </div>
      <el-row>
        <el-col :span="5">
          <div class="content-left" v-loading="groupLoading">
            <div class="dict-header">
              <div class="dict-header-title">字典组</div>
              <div class="dict-header-btns">
                <i class="iconfont refresh" @click="handleGetGroupList">&#xe675;</i>
                <i class="iconfont add" v-permission="['build:dictionary:manage:add']" @click="handleAddGroup">&#xe670;</i>
              </div>
            </div>
            <el-scrollbar height="70vh">
              <div class="dict-list" v-if="groupList.length > 0">
                <div :class="{ 'dict-item': true, active: activeIndex === index }" v-for="(item, index) in groupList" :key="index" @click="handleGroup(index, item)">
                  （ID:{{ item.id }}）{{ item.name }}
                  <div class="icon-right">
                    <i class="iconfont edit" v-permission="['build:dictionary:manage:edit']" @click.stop="handleUpdateGroup(item)">&#xe6e6;</i>
                    <i class="iconfont delete" v-permission="['build:dictionary:manage:delete']" @click.stop="handleDeleteGroup(item)">&#xe718;</i>
                  </div>
                </div>
              </div>
              <el-empty v-else description="暂无字典组">
                <el-button v-permission="['build:dictionary:manage:add']" type="primary" @click="handleAddGroup">去添加</el-button>
              </el-empty>
            </el-scrollbar>
          </div>
        </el-col>
        <el-col :span="19">
          <div class="content-right" v-loading="dictLoading">
            <div class="table-top">
              <div class="table-top-title">字典项（{{ curGroup.name }}）</div>
              <div class="table-top-btns">
                <div class="btns-left">
                  <el-button size="" @click="handleGetDictList">刷新</el-button>
                  <el-button v-permission="['build:dictionary:manage:add']" size="" type="primary" @click="handleAddDict">新增</el-button>
                  <el-button v-permission="['build:dictionary:manage:delete']" size="" type="danger" @click.prevent="handleDeleteDict(selectedList)" :disabled="!selectedList.length > 0">
                    删除
                  </el-button>
                </div>
              </div>
            </div>
            <el-table :data="dictList" border stripe class="table-content" @selection-change="selectedChange" row-key="id" default-expand-all>
              <el-table-column type="selection" />
              <el-table-column prop="dataKey" label="名称" align="center" />
              <el-table-column prop="dataValue" label="值" align="center" />
              <el-table-column prop="description" label="描述" align="center" />
              <el-table-column label="操作" align="center">
                <template #default="scope">
                  <el-button v-permission="['build:dictionary:manage:edit']" size="small" @click="handleUpdateDict(scope.row)">编辑</el-button>
                  <el-button v-permission="['build:dictionary:manage:delete']" size="small" type="danger" @click="handleDeleteDict([scope.row.id])">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-col>
      </el-row>
    </div>
    <!-- 字典组添加弹窗 -->
    <el-dialog :title="groupForm.id ? '编辑字典组' : '添加字典组'" v-model="groupDialog" width="30%" @close="cancle('group')">
      <el-form :model="groupForm" ref="groupFormRef" :rules="formRules" label-width="100px" label-position="right">
        <el-form-item label="字典组名" prop="name">
          <el-input v-model="groupForm.name" placeholder="请输入字典组名"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input type="textarea" rows="3" v-model="groupForm.description" placeholder="字典组描述"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span>
          <el-button @click="groupDialog = false">取消</el-button>
          <el-button type="primary" @click="submitGroup">确认</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 字典值添加/编辑弹窗 -->
    <el-dialog :title="dictForm.id ? '编辑字典项' : '添加字典项'" v-model="dictDialog" width="30%" @close="cancle('dict')">
      <el-form :model="dictForm" ref="dictFormRef" :rules="formRules" label-width="100px" label-position="right">
        <el-form-item label="字典组" prop="dictionaryGroupId">
          <el-select v-model="dictForm.dictionaryGroupId" placeholder="请选择" disabled>
            <el-option v-for="item in groupList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="选项名" prop="dataKey">
          <el-input v-model="dictForm.dataKey" placeholder="请输入选项名"></el-input>
        </el-form-item>
        <el-form-item label="选项值">
          <el-input v-model="dictForm.dataValue" type="textarea" rows="3" placeholder="请输入选项值"></el-input>
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="dictForm.description" type="textarea" rows="3" placeholder="选项描述"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span>
          <el-button @click="dictDialog = false">取消</el-button>
          <el-button type="primary" @click="submitDict">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { selectListDict, insertDict, deleteDict, updateDict, selectListDictGroup, insertDictGroup, deleteDictGroup, updateDictGroup } from '@/api/dictionary'
import { ElMessage, ElMessageBox } from 'element-plus'

// 当前字典组
const curGroup = ref({})
// 切换字典组
const activeIndex = ref()
const handleGroup = (index, item) => {
  activeIndex.value = index
  curGroup.value = JSON.parse(JSON.stringify(item))
  dictList.value = []
  handleGetDictList()
}
// 字典组获取
const groupLoading = ref(false)
const groupList = ref([])
const handleGetGroupList = async () => {
  groupLoading.value = true
  const res = await selectListDictGroup()
  if (res.code === 20000) {
    groupList.value = res.data
    if (groupList.value.length > 0) {
      handleGroup(0, groupList.value[0])
    } else {
      curGroup.value = {}
    }
  }
  groupLoading.value = false
}
// 字典项获取
const dictLoading = ref(false)
const dictList = ref([])
const handleGetDictList = async () => {
  dictLoading.value = true
  const res = await selectListDict({ dictionaryGroupId: curGroup.value.id })
  if (res.code === 20000) {
    dictList.value = res.data
  }
  dictLoading.value = false
}
// 添加/编辑字典组
const groupDialog = ref(false)
const handleAddGroup = () => {
  delete groupForm.id
  groupForm.name = ''
  groupForm.description = ''
  groupDialog.value = true
}
const groupFormRef = ref(null)
const groupForm = reactive({
  name: '',
  description: ''
})
const formRules = reactive({
  name: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
  dataKey: [{ required: true, message: '选项名不能为空', trigger: 'blur' }],
  dataValue: [{ required: true, message: '选项值不能为空', trigger: 'blur' }],
  dictionaryGroupId: [{ required: true, message: '字典组不能为空', trigger: 'blur' }]
})
const submitGroup = () => {
  if (!groupFormRef.value) return
  groupFormRef.value.validate(async valid => {
    if (valid) {
      let res
      if (groupForm.id) {
        res = await updateDictGroup(groupForm)
      } else {
        res = await insertDictGroup(groupForm)
      }
      if (res.success) {
        ElMessage({
          message: '操作成功',
          type: 'success'
        })
        groupDialog.value = false
        handleGetGroupList()
      } else {
        ElMessage({
          message: res.message,
          type: 'error'
        })
      }
    }
  })
}
const handleUpdateGroup = row => {
  Object.assign(groupForm, row)
  groupDialog.value = true
}
const handleDeleteGroup = async row => {
  ElMessageBox.confirm('<div><p style="font-size: 16px;margin-bottom: 15px;">此操作将永久删除选中字典组，是否继续？</p></div>', '删除确认', {
    dangerouslyUseHTMLString: true,
    confirmButtonText: '确认',
    cancelButtonText: '取消'
  })
    .then(async () => {
      const res = await deleteDictGroup({ ids: [row.id], isAllChoose: false })
      if (res.code === 20000) {
        ElMessage({
          message: '删除成功',
          type: 'success'
        })
        groupDialog.value = false
        handleGetGroupList()
      } else {
        ElMessage({
          message: '删除失败',
          type: 'error'
        })
      }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除'
      })
    })
}
// 新增字典项
const dictFormRef = ref(null)
const dictDialog = ref(false)
const defaultDictForm = reactive({
  dataKey: null,
  dataValue: null,
  description: null,
  dictionaryGroupId: null
})
const dictForm = ref(Object.assign({}, defaultDictForm))
const handleAddDict = async () => {
  dictForm.value = Object.assign({}, defaultDictForm)
  dictForm.value.dictionaryGroupId = curGroup.value.id
  dictDialog.value = true
}
const submitDict = () => {
  if (!dictFormRef.value) return
  dictFormRef.value.validate(async valid => {
    if (valid) {
      try {
        dictForm.value.dataValue = JSON.stringify(JSON.parse(dictForm.value.dataValue.replace(/\r\n|\n|\r|\t/gm, '')))
      } catch {
        console.error(dictForm.value.dataValue)
      }
      let res
      if (dictForm.value.id) {
        res = await updateDict(dictForm.value)
      } else {
        res = await insertDict(dictForm.value)
      }
      if (res.success) {
        ElMessage({
          message: res.message,
          type: 'success'
        })
        dictDialog.value = false
        handleGetDictList()
      }
    }
  })
}
// 编辑更新字典项
const handleUpdateDict = async row => {
  dictForm.value = Object.assign({}, row)
  dictDialog.value = true
}
// 删除字典项
const handleDeleteDict = async data => {
  ElMessageBox.confirm('<div><p style="font-size: 16px;margin-bottom: 15px;">此操作将永久删除选中字典项，是否继续？</p></div>', '删除确认', {
    dangerouslyUseHTMLString: true,
    confirmButtonText: '确认',
    cancelButtonText: '取消'
  })
    .then(async () => {
      let res
      if (data) {
        res = await deleteDict({ ids: data, isAllChoose: false })
      }
      if (res.code === 20000) {
        ElMessage({
          message: '删除成功',
          type: 'success'
        })
        dictDialog.value = false
        handleGetDictList()
      } else {
        ElMessage({
          message: '删除失败',
          type: 'error'
        })
      }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除'
      })
    })
}
// 列表勾选
const selectedList = ref([])
const selectedChange = e => {
  selectedList.value = e.map(item => item.id)
}
// 弹窗取消
const cancle = type => {
  switch (type) {
    case 'group':
      groupFormRef.value.resetFields()
      break
    case 'dict':
      dictFormRef.value.resetFields()
      break
  }
}
onMounted(() => {
  handleGetGroupList()
})
</script>

<style lang="scss" scoped>
.system-dict {
  .content-left {
    .dict-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 10px;
      padding: 0 10px;
      .dict-header-title {
        font-size: 16px;
        font-weight: 600;
      }
      .dict-header-btns {
        display: flex;
        align-items: center;
        i {
          cursor: pointer;
        }
        .add {
          margin-left: 8px;
          font-size: 22px;
        }
      }
    }
    .dict-list {
      .dict-item {
        display: flex;
        align-items: center;
        list-style: none;
        box-sizing: border-box;
        padding: 10px 35px 10px 10px;
        margin: 0 10px 10px 0;
        font-size: 13px;
        border-radius: 4px;
        position: relative;
        background: #f7f7f7;
        cursor: default;
        .icon-right {
          position: absolute;
          right: 5px;
          top: 50%;
          transform: translateY(-50%);
          font-size: 12px;
          i {
            cursor: pointer;
          }
          .edit {
            color: #4d99f2;
          }
          .delete {
            margin-left: 8px;
            color: #f56c6c;
          }
        }
        &:hover {
          color: #333333;
        }
        &.active {
          color: #fff;
          background: $mainColor;
          i {
            color: #fff !important;
          }
        }
      }
    }
  }
  .content-right {
    .table-top {
      margin-bottom: 10px;
      .table-top-title {
        margin-bottom: 10px;
        font-size: 16px;
        font-weight: 600;
        text-align: center;
      }
      .table-top-btns {
        display: flex;
        justify-content: space-between;
        align-items: center;
        .btns-right {
          display: flex;
          align-items: center;
          .search-btn {
            margin-left: 10px;
          }
        }
      }
    }
  }
}

::v-deep .el-table th.el-table__cell {
  background-color: #f2f2f2;
  color: #333333;
}

::v-deep(.el-table__row:not([class*='el-table__row--level-'])) {
  // td:nth-child(2) {
  //   padding-left: 20px;
  // }
}
</style>